package com.fzg.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fzg.common.enums.ResponseWrapper;
import com.fzg.common.model.param.user.LoginParam;
import com.fzg.common.model.param.user.QueryUserConcernListParam;
import com.fzg.common.model.param.user.Register;
import com.fzg.common.model.param.user.UpdateUserNickNameParam;
import com.fzg.common.model.result.user.GetUserInfoByAidResult;
import com.fzg.common.model.result.user.QueryUserConcernListResult;
import com.fzg.common.model.result.user.QueryUserConcernListResultItem;
import com.fzg.common.model.result.user.UserAllMoment;
import com.fzg.common.tool.JwtUtil;
import com.fzg.common.tool.MD5Tool;
import com.fzg.entity.*;
import com.fzg.mapper.*;
import com.fzg.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.time.ZoneId;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author fzg
 * @since 2022-06-17
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DiaryMapper diaryMapper;

    @Autowired
    private BlogMapper blogMapper;

    @Autowired
    private UserGuanzhuMapper userGuanzhuMapper;

    @Autowired
    private TagMapper tagMapper;

    @Autowired
    private WangYiYunService wangYiYunService;

    /**
     * 用户登陆
     *
     * @param param 参数
     * @return ResponseWrapper
     */
    @Override
    public ResponseWrapper login(LoginParam param) {
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getUserName, param.getUserName())
                .eq(User::getUserPassword, MD5Tool.getMD5(param.getUserPassword()))
        );
        if (user == null){
            return ResponseWrapper.markCustomError("用户名或密码错误！");
        }else {
            HashMap<String, String> map = new HashMap<>();
            map.put("aid",user.getAid().toString());
            String token = JwtUtil.getToken(map);
            return ResponseWrapper.markCustomSuccess("登陆成功！",token);
        }
    }

    /**
     * 用户注册
     *
     * @param param 参数
     * @return ResponseWrapper
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseWrapper register(Register param) {

        // 验证手机验证码是否正确
        ResponseWrapper responseWrapper = wangYiYunService.verifyShortMessageCode(param.getUserPhone(), param.getCaptcha());
        HashMap<String,Object> data = (HashMap<String, Object>) responseWrapper.getData();
        if(data.get("data").equals(true)){
            int insert = userMapper.insert(new User() {{
                setUserName(param.getUserName());
                setUserPassword(MD5Tool.getMD5(param.getUserPassword()));
                setPhone(param.getUserPhone());
                setGender(0);
            }});
            if (insert > 0){
                return ResponseWrapper.markCustomSuccess("注册成功！");
            }else {
                return ResponseWrapper.markCustomError("注册失败！");
            }
        }else {
            return ResponseWrapper.markCustomError(data.get("message").toString());
        }
    }

    /**
     * 验证用户名是否唯一
     *
     * @param userName  用户名
     * @return ResponseWrapper
     */
    @Override
    public ResponseWrapper checkUserName(String userName) {
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUserName, userName));
        if (user != null){
            return ResponseWrapper.markSuccess(true);
        }else {
            return ResponseWrapper.markSuccess(false);
        }
    }

    /**
     * 验证手机号是否被注册
     *
     * @param userPhone 手机号
     * @return ResponseWrapper
     */
    @Override
    public ResponseWrapper checkPhone(String userPhone) {
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getPhone, userPhone));
        if (user != null){
            return ResponseWrapper.markSuccess(true);
        }else {
            return ResponseWrapper.markSuccess(false);
        }
    }

    /**
     * 获取这个用户所有信息
     *
     * @param userAid 参数
     * @return ResponseWrapper
     */
    @Override
    public ResponseWrapper getUserInfoByAid(HttpServletRequest request, Integer userAid) {
        GetUserInfoByAidResult result = new GetUserInfoByAidResult();

        // 这个用户是否是当前登陆的用户
        result.setIsCurrentLoginUser(JwtUtil.getTokenId(request.getHeader("token")).equals(userAid));

        User user = userMapper.selectById(userAid);
        // 用户昵称
        result.setUserNickName(user.getNickName() == null ? user.getUserName() : user.getNickName());

        // 用户头像
        result.setUserAvatar(user.getAvatar() == null ? "https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg" : user.getAvatar());

        // 用户背景图URL
        result.setUserBg(user.getBackImage() == null ? "https://img2.baidu.com/it/u=3305896652,243597795&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500" : user.getBackImage());

        // 用户名
        result.setUserName(user.getUserName());

        // 这个用户注册这个app多少天了
        Date createTime = Date.from(user.getCreateTime().atZone(ZoneId.systemDefault()).toInstant());
        long time = createTime.getTime();
        long time1 = new Date().getTime();
        long dayCount = (time1-time)/1000/60/60/24;
        result.setBirthCount((int) dayCount);

        // 有多少篇日记
        result.setDiaryCount(Math.toIntExact(diaryMapper.selectCount(new LambdaQueryWrapper<Diary>().eq(Diary::getUserAid, userAid))));

        // 多少篇博客
        result.setBlogCount(Math.toIntExact(blogMapper.selectCount(new LambdaQueryWrapper<Blog>().eq(Blog::getUserAid,userAid))));

        // 该用户关注了多少用户
        result.setUserConcern(Math.toIntExact(userGuanzhuMapper.selectCount(new LambdaQueryWrapper<UserGuanzhu>().eq(UserGuanzhu::getGuanzhuUserAid, userAid))));

        // 该用户被多少用户关注
        result.setUserConcerned(Math.toIntExact(userGuanzhuMapper.selectCount(new LambdaQueryWrapper<UserGuanzhu>().eq(UserGuanzhu::getBeiguanzhuUserAid, userAid))));

        // 当前登陆的用户有没有关注传过来的这个用户
        List<UserGuanzhu> guanzhus = userGuanzhuMapper.selectList(new LambdaQueryWrapper<UserGuanzhu>()
                .eq(UserGuanzhu::getGuanzhuUserAid, JwtUtil.getTokenId(request.getHeader("token")))
                .eq(UserGuanzhu::getBeiguanzhuUserAid, userAid)
        );
        if (guanzhus.size() > 0){
            result.setGuanzhuOrWeiGuanZhu("已关注");
        }else {
            result.setGuanzhuOrWeiGuanZhu("关" + " " + "注");
        }

        // 用户标签
        ArrayList<String> tags = new ArrayList<>();
        List<Tag> tagList = tagMapper.selectList(new LambdaQueryWrapper<Tag>().eq(Tag::getUserAid, userAid));
        for (Tag tag : tagList) {
            tags.add(tag.getName());
        }
        result.setUserTags(tags);


        // 该用户的所有瞬间（包含日记，博客和其他）
        List<Diary> diaries = diaryMapper.selectList(new LambdaQueryWrapper<Diary>().eq(Diary::getUserAid, userAid));
        List<Blog> blogs = blogMapper.selectList(new LambdaQueryWrapper<Blog>().eq(Blog::getUserAid, userAid));
        ArrayList<UserAllMoment> momentList = new ArrayList<>();

        for (Diary diary : diaries) {
            UserAllMoment moment = new UserAllMoment();
            moment.setMomentAid(diary.getAid());
            moment.setContent(diary.getContent());
            moment.setCreateTime(diary.getCreateTime().toString().substring(0,10) + " " + diary.getCreateTime().toString().substring(11));

            if (diary.getDiaryImgUrl() == null){  // 如果该日记没有图片
                ArrayList<String> images = new ArrayList<>();
                moment.setImageList(images);
            }else {
                boolean flag = false;
                for (int i = 0; i < diary.getDiaryImgUrl().length(); i++) {
                    String ch = String.valueOf(diary.getDiaryImgUrl().charAt(i));
                    if (ch.equals(";")) {
                        flag = true;
                        break;
                    }
                }
                if (flag){ // 说明有两张及两张以上的图片
                    String[] picUrls = diary.getDiaryImgUrl().split(";");
                    ArrayList<String> images = new ArrayList<>();
                    Collections.addAll(images,picUrls);
                    moment.setImageList(images);
                }else { // 说明只有一张
                    ArrayList<String> images = new ArrayList<>();
                    images.add(diary.getDiaryImgUrl());
                    moment.setImageList(images);
                }
            }
            momentList.add(moment);
        }

        for (Blog blog : blogs) {
            UserAllMoment moment = new UserAllMoment();
            moment.setMomentAid(blog.getAid());
            moment.setContent(blog.getContent());
            moment.setCreateTime(blog.getCreateTime().toString().substring(0,10) + " " + blog.getCreateTime().toString().substring(11));

            if (blog.getBlogImgurl() == null){
                ArrayList<String> images = new ArrayList<>();
                moment.setImageList(images);
            }else {
                boolean flag = false;
                for (int i = 0; i < blog.getBlogImgurl().length(); i++) {
                    String ch = String.valueOf(blog.getBlogImgurl().charAt(i));
                    if (ch.equals(";")) {
                        flag = true;
                        break;
                    }
                }
                if (flag){ // 说明有两张及两张以上的图片
                    String[] picUrls = blog.getBlogImgurl().split(";");
                    ArrayList<String> images = new ArrayList<>();
                    Collections.addAll(images,picUrls);
                    moment.setImageList(images);
                }else { // 说明只有一张
                    ArrayList<String> images = new ArrayList<>();
                    images.add(blog.getBlogImgurl());
                    moment.setImageList(images);
                }
            }
            momentList.add(moment);
        }
        // momentList按日期排序
        momentList.sort((t1, t2) -> t2.getCreateTime().compareTo(t1.getCreateTime()));

        result.setMomentList(momentList);

        return  ResponseWrapper.markSuccess(result);

    }

    /**
     * 修改用户的昵称
     *
     * @param param 参数
     * @return ResponseWrapper
     */
    @Override
    public ResponseWrapper updateUserNickName(UpdateUserNickNameParam param) {
        User user = userMapper.selectById(param.getUserAid());
        User user1 = new User();
        BeanUtils.copyProperties(user,user1);
        user1.setNickName(param.getNickName());
        int updateById = userMapper.updateById(user1);
        if (updateById > 0){
            return ResponseWrapper.markCustomSuccess("修改成功！");
        }else {
            return ResponseWrapper.markCustomError("修改失败！请稍后再试！");
        }
    }

    /**
     * 查询用户的关注用户列表和被关注用户列表
     *
     * @param request 参数
     * @param param 参数
     * @return ResponseWrapper
     */
    @Override
    public ResponseWrapper queryUserConcernList(HttpServletRequest request, QueryUserConcernListParam param) {

        // 返回结果
        QueryUserConcernListResult result = new QueryUserConcernListResult();

        // 当前登陆用户的aid
        Integer currentUserAid = JwtUtil.getTokenId(request.getHeader("token"));

        if (param.getUserAid().equals(currentUserAid)){
            result.setTaOrMe("我");
        }else {
            result.setTaOrMe("ta");
        }

        ArrayList<QueryUserConcernListResultItem> userList = new ArrayList<>();

        // 用户列表
        if (param.getState().equals(1)){ // 查询该用户关注的用户列表

            List<UserGuanzhu> guanzhuList = userGuanzhuMapper.selectList(new LambdaQueryWrapper<UserGuanzhu>()
                    .eq(UserGuanzhu::getGuanzhuUserAid, param.getUserAid())
            );

            if (param.getSearchKey().equals("")){
                for (UserGuanzhu userGuanzhu : guanzhuList) {
                    QueryUserConcernListResultItem resultItem = new QueryUserConcernListResultItem();

                    User user = userMapper.selectById(userGuanzhu.getBeiguanzhuUserAid());

                    resultItem.setUser(user);
                    List<UserGuanzhu> guanzhus = userGuanzhuMapper.selectList(new LambdaQueryWrapper<UserGuanzhu>()
                            .eq(UserGuanzhu::getGuanzhuUserAid, currentUserAid)
                            .eq(UserGuanzhu::getBeiguanzhuUserAid, user.getAid())
                    );
                    if (guanzhus.size() > 0){
                        resultItem.setIsConcerned("已关注");
                    }else {
                        resultItem.setIsConcerned("关注");
                    }

                    // 这个用户注册这个app多少天了
                    Date createTime = Date.from(user.getCreateTime().atZone(ZoneId.systemDefault()).toInstant());
                    long time = createTime.getTime();
                    long time1 = new Date().getTime();
                    long dayCount = (time1-time)/1000/60/60/24;
                    resultItem.setBirthDayCount((int) dayCount);

                    // 这个用户有多少瞬间
                    Long diaryCount = diaryMapper.selectCount(new LambdaQueryWrapper<Diary>().eq(Diary::getUserAid, user.getAid()));
                    Long blogCount = blogMapper.selectCount(new LambdaQueryWrapper<Blog>().eq(Blog::getUserAid, user.getAid()));
                    resultItem.setMomentCount((int)(diaryCount + blogCount));

                    userList.add(resultItem);
                }
            }else {
                ArrayList<User> users = new ArrayList<>();
                for (UserGuanzhu userGuanzhu : guanzhuList) {
                    User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                            .eq(User::getAid, userGuanzhu.getGuanzhuUserAid())
                            .like(User::getUserName, param.getSearchKey())
                            .or()
                            .like(User::getNickName, param.getSearchKey())
                    );
                    if (user != null){
                        users.add(user);
                    }
                }
                for (User user : users) {
                    QueryUserConcernListResultItem resultItem = new QueryUserConcernListResultItem();

                    resultItem.setUser(user);
                    List<UserGuanzhu> guanzhus = userGuanzhuMapper.selectList(new LambdaQueryWrapper<UserGuanzhu>()
                            .eq(UserGuanzhu::getGuanzhuUserAid, currentUserAid)
                            .eq(UserGuanzhu::getBeiguanzhuUserAid, user.getAid())
                    );
                    if (guanzhus.size() > 0){
                        resultItem.setIsConcerned("已关注");
                    }else {
                        resultItem.setIsConcerned("关注");
                    }

                    // 这个用户注册这个app多少天了
                    Date createTime = Date.from(user.getCreateTime().atZone(ZoneId.systemDefault()).toInstant());
                    long time = createTime.getTime();
                    long time1 = new Date().getTime();
                    long dayCount = (time1-time)/1000/60/60/24;
                    resultItem.setBirthDayCount((int) dayCount);

                    // 这个用户有多少瞬间
                    Long diaryCount = diaryMapper.selectCount(new LambdaQueryWrapper<Diary>().eq(Diary::getUserAid, user.getAid()));
                    Long blogCount = blogMapper.selectCount(new LambdaQueryWrapper<Blog>().eq(Blog::getUserAid, user.getAid()));
                    resultItem.setMomentCount((int)(diaryCount + blogCount));

                    userList.add(resultItem);
                }
            }
        }else { // state != 1 插叙该用户被关注的用户列表
            List<UserGuanzhu> guanzhuList = userGuanzhuMapper.selectList(new LambdaQueryWrapper<UserGuanzhu>()
                    .eq(UserGuanzhu::getBeiguanzhuUserAid, param.getUserAid())
            );

            if (param.getSearchKey().equals("")){
                for (UserGuanzhu userGuanzhu : guanzhuList) {
                    QueryUserConcernListResultItem resultItem = new QueryUserConcernListResultItem();

                    User user = userMapper.selectById(userGuanzhu.getGuanzhuUserAid());

                    resultItem.setUser(user);
                    List<UserGuanzhu> guanzhus = userGuanzhuMapper.selectList(new LambdaQueryWrapper<UserGuanzhu>()
                            .eq(UserGuanzhu::getGuanzhuUserAid, currentUserAid)
                            .eq(UserGuanzhu::getBeiguanzhuUserAid, user.getAid())
                    );
                    if (guanzhus.size() > 0){
                        resultItem.setIsConcerned("已关注");
                    }else {
                        resultItem.setIsConcerned("关注");
                    }

                    // 这个用户注册这个app多少天了
                    Date createTime = Date.from(user.getCreateTime().atZone(ZoneId.systemDefault()).toInstant());
                    long time = createTime.getTime();
                    long time1 = new Date().getTime();
                    long dayCount = (time1-time)/1000/60/60/24;
                    resultItem.setBirthDayCount((int) dayCount);

                    // 这个用户有多少瞬间
                    Long diaryCount = diaryMapper.selectCount(new LambdaQueryWrapper<Diary>().eq(Diary::getUserAid, user.getAid()));
                    Long blogCount = blogMapper.selectCount(new LambdaQueryWrapper<Blog>().eq(Blog::getUserAid, user.getAid()));
                    resultItem.setMomentCount((int)(diaryCount + blogCount));

                    userList.add(resultItem);
                }
            }else {
                ArrayList<User> users = new ArrayList<>();
                for (UserGuanzhu userGuanzhu : guanzhuList) {
                    User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                            .eq(User::getAid, userGuanzhu.getGuanzhuUserAid())
                            .like(User::getUserName, param.getSearchKey())
                            .or()
                            .like(User::getNickName, param.getSearchKey())
                    );
                    if (user != null) {
                        users.add(user);
                    }
                }
                for (User user : users) {
                    QueryUserConcernListResultItem resultItem = new QueryUserConcernListResultItem();

                    resultItem.setUser(user);
                    List<UserGuanzhu> guanzhus = userGuanzhuMapper.selectList(new LambdaQueryWrapper<UserGuanzhu>()
                            .eq(UserGuanzhu::getGuanzhuUserAid, currentUserAid)
                            .eq(UserGuanzhu::getBeiguanzhuUserAid, user.getAid())
                    );
                    if (guanzhus.size() > 0) {
                        resultItem.setIsConcerned("已关注");
                    } else {
                        resultItem.setIsConcerned("关注");
                    }

                    // 这个用户注册这个app多少天了
                    Date createTime = Date.from(user.getCreateTime().atZone(ZoneId.systemDefault()).toInstant());
                    long time = createTime.getTime();
                    long time1 = new Date().getTime();
                    long dayCount = (time1 - time) / 1000 / 60 / 60 / 24;
                    resultItem.setBirthDayCount((int) dayCount);

                    // 这个用户有多少瞬间
                    Long diaryCount = diaryMapper.selectCount(new LambdaQueryWrapper<Diary>().eq(Diary::getUserAid, user.getAid()));
                    Long blogCount = blogMapper.selectCount(new LambdaQueryWrapper<Blog>().eq(Blog::getUserAid, user.getAid()));
                    resultItem.setMomentCount((int) (diaryCount + blogCount));

                    userList.add(resultItem);
                }
            }
        }
        result.setUserList(userList);
        return ResponseWrapper.markSuccess(result);
    }

    /**
     * 测试视图
     */
    @Override
    public ResponseWrapper getData() {
        List<Map<String, Object>> data = userMapper.getData();
        return ResponseWrapper.markSuccess(data);
    }
}
